﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
using Vibz.TeamAssignment.Common.Entity;
using System.IO;

namespace Vibz.TeamAssignment
{
    internal enum RecipientType { To, CC, BCC }
    internal class MailProcessor
    {
        public static void SendMail(string domain, string subject, string body, Dictionary<string, RecipientType> recipients)
        {
            SendMail(domain, subject, body, recipients, null);
        }
        public static void SendMail(string domain, string subject, string body, Dictionary<string, RecipientType> recipients, 
            Dictionary<string, FileInfo> attachments)
        {
            try
            {
                Outlook.Application oApp = new Outlook.Application();

                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                Outlook.Recipient oRecip = null;
                foreach(string rec in recipients.Keys)
                {
                    oRecip = (Outlook.Recipient)oMsg.Recipients.Add(rec + "@" + domain);
                    switch(recipients[rec])
                    {
                        case RecipientType.CC:
                            oRecip.Type = (int)Outlook.OlMailRecipientType.olBCC;
                            break;
                        case RecipientType.BCC:
                            oRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
                            break;
                        case RecipientType.To:
                            oRecip.Type = (int)Outlook.OlMailRecipientType.olTo;
                            break;
                    }
                    oRecip.Resolve();
                }

                oMsg.Subject = subject;
                oMsg.Body = body;

                Outlook.Attachment oAttach = null;
                if(attachments != null)
                {
                    foreach(string atchName in attachments.Keys)
                    {
                        int iPosition = (int)oMsg.Body.Length + 1;
                        int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                        oAttach = oMsg.Attachments.Add(attachments[atchName].FullName, iAttachType, iPosition, atchName);
                    }
                }
                oMsg.Save();
                oMsg.Send();

                oRecip = null;
                oAttach = null;
                oMsg = null;
                oApp = null;
            }
            catch(Exception e)
            {
                Console.WriteLine("Mail could not be sent. ", e);
            }
        }
    }
}
